package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollQueryBlog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private IBlogService blogService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryUserInfo(blog);
            this.blogLikedInfo(blog);
        });
        return Result.ok(records);
    }

    public void queryUserInfo(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result queryByBlogId(Long id) {
        Blog blog = blogService.getById(id);
        if (blog == null) {
            return Result.fail("博客笔记不存在！");
        }
        //查询用户对应信息
        queryUserInfo(blog);
        //查询用户的点赞情况
        blogLikedInfo(blog);
        return Result.ok(blog);
    }

    public void blogLikedInfo(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return ;
        }
        Long id = blog.getId();
        Long userId = user.getId();
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
        blog.setIsLike(score!=null);
    }

    @Override
    public Result likeBlog(Long id) {
        //查询id对应的博客信息
        Blog blog = getById(id);
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //查询redis中是否存在对应的userId，查到代表点赞过，然后点赞数量减一
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
        if (score!=null) {
            boolean isSuceess = blogService.update().setSql("liked=liked-1").eq("id", id).update();
            if (isSuceess) {
                //把该用户点赞信息从redis中移除
                stringRedisTemplate.opsForZSet().remove(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
            }
        }else {
            //没有点赞过，点赞数量+1
            boolean isSuceess = blogService.update().setSql("liked=liked+1").eq("id", id).update();
            if (isSuceess) {
                stringRedisTemplate.opsForZSet().add(RedisConstants.BLOG_LIKED_KEY + id, userId.toString(),System.currentTimeMillis());
            }
        }
        return Result.ok();
    }

    @Override
    //查询top5的点赞
    public Result BlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> set = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        //拿出set中的用户id
        if (set == null || set.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = set.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", ids);
        //根据id查询对应的用户
        List<UserDTO> userDTOList = userService.query()
                .in("id",ids).last("ORDER BY FIELD(id,"+join+")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());


        return Result.ok(userDTOList);
    }

    @Override
    //新增博客笔记
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("新增博客笔记失败!");
        }
        //获取到当前登录用户的所有粉丝
        List<Follow> followList = followService.query().eq("follow_user_id", user.getId()).list();
        //向每一个用户发消息
        for (Follow follow : followList) {
            Long userId = follow.getUserId();
            String key="feed:"+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result limitQueryBlog(Long maxTime, Integer offset) {
        //获取当前登录用户的id
        Long userId = UserHolder.getUser().getId();
        String key=RedisConstants.FEED_KEY+userId;
        //获取当前用户的收件箱中的信息
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
                .opsForZSet().reverseRangeByScoreWithScores(key, 0, maxTime, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        List<Long> ids=new ArrayList<>(typedTuples.size());
        //每一对元组中存入的是对应的id和score
        long minTime=0;
        //偏移量
        int os=1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(Objects.requireNonNull(tuple.getValue())));
           long time= Objects.requireNonNull(tuple.getScore()).longValue();
           if (time==minTime){
               os++;
           }else {
               minTime=time;
               os=1;
           }
        }
        //根据id查询blog
        String join = StrUtil.join(",", ids);
        List<Blog> blogList = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        for (Blog blog : blogList) {
            //查询用户对应信息
            queryUserInfo(blog);
            //查询用户的点赞情况
            blogLikedInfo(blog);
        }
        //封装返回数据
        ScrollQueryBlog queryBlog = new ScrollQueryBlog();
        queryBlog.setList(blogList);
        queryBlog.setOffset(os);
        queryBlog.setMinTime(minTime);
        log.info("成功查询到{}条博客数据，minTime: {}, offset: {}", blogList.size(), minTime, os);
        return Result.ok(queryBlog);
    }
}
